﻿using System;
using System.Linq;
using IterationLife.System.Models;
using IterationLife.System.Repositories;
using Util.Exceptions;

namespace IterationLife.System.Services
{
    public class VerificationCodeManager : IVerificationCodeManager
    {
        protected internal IVerificationCodeRepository Repository { get; set; }

        public VerificationCodeManager(IVerificationCodeRepository repository)
        {
            Repository = repository;
        }

        public void CheckCode(string phone, string purpose, string code)
        {
            var nowTime = DateTime.Now;
            var verficationCode = Repository.Single(d => d.Mobile == phone
            && d.Purpose == purpose && d.Code == code
            && !d.IsUsed && d.ExpirationTime > nowTime);
            if (verficationCode == null)
                throw new Warning("验证码不正确");
            verficationCode.IsUsed = true;
        }

        public string GenerateCode(string phone, string purpose)
        {
            var limitTime = DateTime.Now.AddMinutes(-1);
            var isLimit = Repository.Find().Any(d => d.Mobile == phone && d.Purpose == purpose && d.CreationTime > limitTime);
            if (isLimit)
                throw new Warning("过于频繁申请验证码，请1分钟后重试");

            var verificationCode = new VerificationCode(Guid.NewGuid())
            {
                Mobile = phone,
                Purpose = purpose,
                Code = new Random().Next(100000, 999999).ToString(),
                ExpirationTime = DateTime.Now.AddMinutes(10),
                CreationTime = DateTime.Now,
            };
            Repository.Add(verificationCode);
            return verificationCode.Code;
        }
    }
}
